//
//  RouteNavigationViewController.m
//  TMapDemo
//
//  Created by zhaoxibo on 13-5-22.
//
//

#import "RouteNavigationViewController.h"
#import "MyAnnotation.h"
#import "TPolylineView.h"

@interface RouteNavigationViewController ()<TMapViewDelegate, TDrivingRouteDelegate,UIAlertViewDelegate>

@end

@implementation RouteNavigationViewController



- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)backMethod
{
    [self removeAnnotation];
    [self removeOverlays];
    
    self.distanceLabel = nil;
    self.annotation = nil;
    self._segmentControl = nil;
    
    self._mapView.delegate = nil;
    self._mapView = nil;
    
    self._drivingRoute.delegate = nil;
    self._drivingRoute = nil;
    
    self._arrAnnotation = nil;
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"线路详情";

    self._mapView.delegate = self;
    self._drivingRoute.delegate = self;
    self.navigationItem.rightBarButtonItem = nil;
    // Do any additional setup after loading the view from its nib.
    
    // 初始起点终点经纬度

}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self._mapView setFrame:CGRectMake(0, 69 , CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - 69)];

    if (self._drivingRoute == nil ) {
        self._drivingRoute = [[TDrivingRoute alloc] init];
        self._drivingRoute.delegate = self;
    }
//    TDrivingRouteType drivingRouteType = self._segmentControl.selectedSegmentIndex;
    [self._segmentControl addTarget:self action:@selector(setDrivingRoute:) forControlEvents:UIControlEventValueChanged];  //添加委托方法
    [self setDrivingRoute:self._segmentControl];

}

- (void)setDrivingRoute:(UISegmentedControl *)segmentControl
{
    TDrivingRouteType drivingRouteType = self._segmentControl.selectedSegmentIndex;
    NSLog(@"segmentControl.selectedSegmentIndex - %d",segmentControl.selectedSegmentIndex);
    [self._drivingRoute startRoute:self.annotation.coordinate end:self.location mid:nil midCount:0 type:drivingRouteType];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [super viewDidUnload];
}


#pragma mark 地图地位
- (IBAction)locadiong:(id)sender
{
    [self._mapView StartGetPosition];
}

#pragma mark 缩小地图
- (IBAction)zoomIn:(id)sender
{
    [self._mapView MapScaleSub];
}

#pragma mark 放大地图
- (IBAction)zoomOut:(id)sender
{
    [self._mapView MapScaleAdd];
}


#pragma mark
// 清空标注
- (void)removeAnnotation {
    int iSize = [self._arrAnnotation count];
    if (iSize) {
        for (int i = iSize - 1; i >= 0; --i) {
            id item = [self._arrAnnotation objectAtIndex:i];
            [self._mapView removeAnnotation:item];
        }
    }
    [self._arrAnnotation removeAllObjects];
}

- (void)removeOverlays {
    NSArray *arrvo = [self._mapView overlays];
    if (arrvo.count) {
        [self._mapView removeOverlay:[arrvo objectAtIndex:0]];
        [self._mapView setNeedsDisplay];
    }
}

- (TOverlayView *)mapView:(TMapView *)mapView viewForOverlay:(id <TOverlay>)overlay {
    TPolylineView *lineview = [[TPolylineView alloc] initWithPolyline:overlay mapView:mapView];
    lineview.lineWidth = 4;
    lineview.strokeColor = [UIColor redColor];
    return lineview;
}

// 用户实现创建一个动态标注视图
- (TAnnotationView *)mapView:(TMapView *)mapView viewForAnnotation:(id <TAnnotation>)annotation {
    if ([self._arrAnnotation indexOfObject:annotation] != NSNotFound) {
        static NSString *CellIdentifier = @"drivingroute";
        TAnnotationView *annotationView = [[TAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:CellIdentifier];
        annotationView.image = [UIImage imageNamed:@"icon_routelable_turn"];
        annotationView.selectImage = [UIImage imageNamed:@"icon_routelable_turn"];
        if (self._arrAnnotation[0] == annotation) {
            annotationView.image = [UIImage imageNamed:@"icon_route_start"];
            annotationView.selectImage = [UIImage imageNamed:@"icon_route_start"];
        } else if (self._arrAnnotation[self._arrAnnotation.count - 1] == annotation){
            annotationView.image = [UIImage imageNamed:@"icon_route_end"];
            annotationView.selectImage = [UIImage imageNamed:@"icon_route_end"];

        }
        if (annotation == self.annotation) {
            annotationView.image = [UIImage imageNamed:@"icon_route_start"];
            annotationView.selectImage = [UIImage imageNamed:@"icon_route_start"];
            
        }
        annotationView.canShowCallout = TRUE;
        CGPoint ptoffset = CGPointMake(annotationView.image.size.width / 2, 0);
        annotationView.calloutOffset = ptoffset;
        return annotationView;
    }
    
    return nil;
}

- (void)mapView:(TMapView *)mapView didSelectAnnotationView:(TAnnotationView *)view {
    NSArray *arrSelect = mapView.selectedAnnotations;
    for (int i = 0; i < arrSelect.count; i++) {
        id <TAnnotation> ann = [arrSelect objectAtIndex:i];
        if (ann != view.annotation) {
            [mapView deselectAnnotation:ann animated:YES];
        }
    }
}



#pragma mark -
#pragma mark ---------TDrivingRouteDelegate---------
// 自家规划结果回调函数
- (void)drivingRouteResult:(TDrivingRouteResult *)pDrivingRouteResult
                 errorCode:(int)iErrorCode {
    if (iErrorCode != 0) {
//        _info.text = @"自驾规划失败";
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"" message:@"创建路线错误" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
//        [alertView show];
        [self setDrivingRoute:nil];

        return;
    }
    
    NSString *str1 = nil;
    int iHour = pDrivingRouteResult.costTime / 3600;
    int iMin = (pDrivingRouteResult.costTime - iHour * 3600) / 60;
    if (iHour > 0)
        str1 = [NSString stringWithFormat:@"时间%d小时%2.2d分钟", iHour, iMin];
    else
        str1 = [NSString stringWithFormat:@"时间%d分钟", iMin];
    
    NSString *strMsg = [NSString stringWithFormat:@"全程预计 : %2.2f公里 %@", pDrivingRouteResult.distance, str1];
    self.distanceLabel.text = strMsg;
    // 清空标注
    [self removeAnnotation];
    [self removeOverlays];
    
    CLLocationCoordinate2D startPoi = {0};
    CLLocationCoordinate2D endPoi = {0};
    TDrivingRouteRoad *pRoad = [pDrivingRouteResult.road objectAtIndex:0];
    TDrivingRouteSimpleSegment *pSimpleSegment = nil;
    TDrivingRouteRoadSegment *pRoadSegment = nil;
    int i = 0;
    int iPos = 0;
    int iSize = 0;
    for (; i < [pRoad.simpleSegment count]; i++) {
        pSimpleSegment = [pRoad.simpleSegment objectAtIndex:i];
        iSize += [pSimpleSegment.roadSegment count];
    }
    if (iSize) {
        MyAnnotation *temp = nil;
        self._arrAnnotation = [[NSMutableArray alloc] initWithCapacity:iSize + 2];
        // 起点
        temp = [[MyAnnotation alloc] init];
        temp.title = @"起点";
        temp.coordinate = startPoi;
        [self._arrAnnotation addObject:temp];
        
        // 拐点
        for (; iPos < iSize; ++iPos) {
            // 添加标注
            pRoadSegment = [pRoad.roadSegment objectAtIndex:iPos];
            temp = [[MyAnnotation alloc] init];
            temp.title = [NSString stringWithFormat:@"%d.%@", iPos + 1, pRoadSegment.description];
            //    temp.subtitle = [NSString stringWithFormat:@"(id:%@)", record.strId];
            temp.coordinate = pRoadSegment.turnPoint;
            [self._arrAnnotation addObject:temp];
        }
        
        // 终点
        temp = [[MyAnnotation alloc] init];
        temp.title = @"终点";
        temp.coordinate = endPoi;
        [self._arrAnnotation addObject:temp];
        [self._mapView addAnnotations:self._arrAnnotation];
    }
    
    // 设置地图的显示范围
    [self._mapView setRegion:pDrivingRouteResult.region animated:YES];
    
    if (pRoad.pointCount) {
        TPolyline *line = [TPolyline polylineWithCoordinates:pRoad.shapePoints count:pRoad.pointCount];
        [self._mapView addOverlay:line];
        [self._mapView setNeedsDisplay];
    }
    // 设置列表按钮可用
}

#pragma mark -
#pragma mark ---------MapDrivingRouteListDelegate---------
- (void)MapDrivingRouteListController:(id)sender selectRoadSegment:(TDrivingRouteRoadSegment *)Segment AtIndex:(int)iIndex {
    id item = [self._arrAnnotation objectAtIndex:iIndex];
    [self._mapView selectAnnotation:item animated:YES];
    [self._mapView setCenterCoordinate:Segment.turnPoint];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self setDrivingRoute:nil];
    }
}
@end
